<?php
/**
 *  💡 免责声明：本软件不得用于商业用途，仅做学习交流
 *  ⚠️ 权利声明：本软件由版权人提供产品技术支持
 *  📅 项目编号：NX2025-0135
 */
namespace App\Service\User;

use App\Jobs\PerformanceRewardJob;
use App\Jobs\UpdateUserRevenueJob;
use App\Models\PointSetting;
use App\Models\User;
use App\Service\BaseService;

/**
 *部门业绩相关服务类.
 */
class PerformanceService extends BaseService
{
    /**
     * 用户树收益.
     * @param mixed $amount
     * @param mixed $type
     */
    public function userTreeRevenue(User $user, $amount, $type = 1)
    {
        //TODO 两个表消费 1 商品订单表 2 拼团订单表 跟新整个树收益并且触发等级变更
        UpdateUserRevenueJob::dispatch($user, $amount, $type)
            ->onQueue('update_user_revenue');
    }

    /**
     * 直推奖励 普通商品购买.
     * @param mixed $amount
     */
    public function directPushReward(User $user, $amount)
    {
        $parent = $user->getParent(); //2025-06-19修改内容查看工单
        $setting = PointSetting::query()->first();
//        $parent = $user->queryAncestors()->where('member_level', '>', 0)
//            ->orderBy('distance')
//            ->first();
        $multiple = $amount / $setting->secondary_dividend_points;
        $user->increment('contribution_value', $multiple * 10);
        if ($parent) {
            $amount = bcmul($multiple, $setting->base_number, 2);
            if ($parent) {
                $parentPoint = PointAccountServices::make()->consumption($parent->id, $amount, '新零售直推奖励,积分转换消费余额' . $amount, 3);
                if ($parentPoint) {
                    RewardAccountService::make()->recharge($parent->id, $amount, 2, '新零售直推奖励,积分转换' . $amount);
                }
                $parent->contribution_value +=  $setting->second_level_reward * $multiple;
                $parent->save();
            }


        }
    }

    /**
     * 业绩奖励 普通商品购买 拼团成功奖励.
     * @param mixed $amount
     * @param mixed $type
     */
    public function performanceReward(User $user, $amount, $type = 1)
    {
        //TODO 整个奖励分为两块奖励
        PerformanceRewardJob::dispatch($user, $amount, $type)
            ->onQueue('update_performance_reward');
    }
}
